package com.rsstuan.web.controller;

import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;


@SuppressWarnings("serial")
public class SubscribeServlet extends HttpServlet{
	private Logger LOG = Logger.getLogger(SubscribeServlet.class.getName());
	private HttpClient httpClient;
	public SubscribeServlet() {
		httpClient = new HttpClient();
	}
	public void doGet(HttpServletRequest request, HttpServletResponse response) {
		String feedUrl = request.getParameter("fu");
		String hub = "http://pubsubhubbub.appspot.com/";
		String callBackUrl = "http://rsstuan.appspot.com/pubsub";
		String callBack = callBackUrl + "?fu=" + feedUrl + "&hub=" + hub;

		GetMethod getMethod = new GetMethod(hub);
		try {
			HttpMethodParams params = getMethod.getParams();
			params.setParameter("hub.mode", "subscribe");
			params.setParameter("hub.verify", "async");
			params.setParameter("hub.topic", feedUrl);
			params.setParameter("hub.callback", callBack);
			int code = httpClient.executeMethod(getMethod);
			if (code == 200 || code == 202) {
				response.getWriter().println("send OK, code=" + code);
			}
			else {
				response.getWriter().println("send fail, code=" + code);
			}
			LOG.info("send request to hub=" + hub + " feedUrl=" + feedUrl);

		} catch (Exception e) {
			LOG.log(Level.WARNING, "httpclient send fail, feedUrl=" + feedUrl, e);
		}
		finally {
			getMethod.releaseConnection();
		}
		
	}

}
